package juc.reentryLock;


import juc.Sleeper;
import lombok.extern.slf4j.Slf4j;


//解决哲学家死锁问题
@Slf4j(topic = "c.PhilosopherPlus")
public class PhilosopherPlus extends Thread {
    ChopstickPlus left;
    ChopstickPlus right;
    public PhilosopherPlus(String name, ChopstickPlus left, ChopstickPlus right) {
        super(name);
        this.left = left;
        this.right = right;
    }
    @Override
    public void run() {
        while (true) {
// 尝试获得左手筷子
            if (left.tryLock()) {
                try {
// 尝试获得右手筷子
                    if (right.tryLock()) {
                        try {
                            eat();
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
            }
        }
    }
    private void eat() {
        log.debug("eating...");
        Sleeper.sleep(1);
    }
}
